<?php

// 对字符串进行加盐散列加密
function xmd5($str){
	return md5(md5($str).C('SAFE_SALT'));
}

// 获得当前的url
function get_current_url(){
	$url = "http://" . $_SERVER['SERVER_NAME'];
	$url .= $_SERVER['REQUEST_URI'];
	return $url;
}

// 补全url
function complete_url($url){
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	if(substr($url,0,1) == '.'){
		return $protocol . $_SERVER['SERVER_NAME'].__ROOT__.substr($url,1);
	}
	elseif(substr($url,0,7) != 'http://' && substr($url,0,8) != 'https://'){
		return $protocol . $_SERVER['SERVER_NAME'].$url;
	}
	else{
		return $url;
	}
	
}
// 性别
function get_sex_name($sex){
	$status_str = '';
	switch($sex){
		case 0: $status_str = '保密'; break;
		case 1: $status_str = '男'; break;
		case 2: $status_str = '女'; break;
		default : $status_str = '未知状态';
	}
	return $status_str;
}
// 用户状态
function get_user_status($status){
	$status_str = '';
	switch($status){
		case 0: $status_str = '正常'; break;
		case 1: $status_str = '禁止'; break;
		case 2: $status_str = '删除'; break;
		default : $status_str = '未知状态';
	}
	return $status_str;
}
// 商品类别
function get_product_type($type){
	$status_str = '';
	switch($type){
		case 0: $status_str = '虚拟商品'; break;
		case 1: $status_str = '实体商品'; break;
		default : $status_str = '未知状态';
	}
	return $status_str;
}

// 根据订单状态返回状态信息
function get_order_status($status){
	$status_str = '';
	switch($status){
		case -1: $status_str = '已关闭'; break;
		case 1: $status_str = '待支付'; break;
		case 2: $status_str = '待发货'; break;
		case 3: $status_str = '待确认'; break;
		case 4: $status_str = '已完成'; break;
		default : $status_str = '未知状态';
	}
	return $status_str;
}

// 根据订单提现申请返回状态信息
function get_withdraw_status($status){
	$status_str = '';
	switch($status){
		case -1: $status_str = '已拒绝'; break;
		case 1: $status_str = '待审核'; break;
		case 2: $status_str = '待确认'; break;
		case 3: $status_str = '已完成'; break;
		default : $status_str = '未知状态';
	}
	return $status_str;
}

// 根据等级获取等级名称数组
function get_level_name_arr($config){
	if(!is_array($config)){
		$config = unserialize($config);
	}
	$arr = array();
	foreach($config as $v){
		$arr[] = $v['name'];
	}
	return $arr;
}


// 根据自定义菜单类型返回名称
function get_selfmenu_type($type){
	$type_name = '';
	switch($type){
		case 'click':
			$type_name = '点击推事件';
			break;
		case 'view':
			$type_name = '跳转URL';
			break;
		case 'scancode_push':
			$type_name = '扫码推事件';
			break;
		case 'scancode_waitmsg':
			$type_name = '扫码推事件且弹出“消息接收中”提示框';
			break;
		case 'pic_sysphoto':
			$type_name = '弹出系统拍照发图';
			break;
		case 'pic_photo_or_album':
			$type_name = '弹出拍照或者相册发图';
			break;
		case 'pic_weixin':
			$type_name = '弹出微信相册发图器';
			break;
		case 'location_select':
			$type_name = '弹出地理位置选择器';
			break;
		case 'media_id':
			$type_name = '下发消息（除文本消息）';
			break;
		case 'view_limited':
			$type_name = '跳转图文消息URL';
			break;
		default : $type_name = '不支持的类型';
	}
	return $type_name;
}

//获得财务记录动作名称
function get_finance_action($action){
	$return = '';
	switch($action){
		case 1: $return = '在线充值';break;
		case 2: $return = '余额转出';break;
		case 3: $return = '接受转让';break;
		case 4: $return = '绩效奖励';break;
		//case 5: $return = '全球分红';break;
		case 6: $return = '申请提现';break;
		case 7: $return = '提现退回';break;
		case 8: $return = '订单支付';break;
		case 9: $return = '订单分成';break;
		case 10: $return = '取消订单';break;
		case 11: $return = '取消分成';break;
		default : $return = '未知操作';
	}
	return $return;
}

// 替换身份证为星号***
function get_encrypt_idcard($idcard){
	if(strlen($idcard)==15){
		$idcard = substr_replace($idcard,"*******",6,7);
	}elseif(strlen($idcard)==18){
		$idcard = substr_replace($idcard,"*******",8,7);
	}
	return $idcard;
}
// 替换手机号中间的四位为****
function get_encrypt_mobile($mobile){
	if(strlen($mobile)==11){
		$mobile = substr_replace($mobile,"****",3,4);
	}
	return $mobile;
}
// 替换真实姓名为星号x*  x*y
function get_encrypt_true_name($true_name){
	if(!empty($true_name) && strlen($true_name)>2){
		$true_name = substr_replace($true_name,"*",1,1);
	}
	return $true_name;
}

// 更改用户等级
function update_level($user_info, $config){
	$user = M('user');
	// 如果用户参数是id则查询用户信息
	if(!is_array($user_info)){
		$user_info = $user -> find(intval($user_info));
		if(!$user_info){
			return false;
		}
	}
	
	if(!$config)$config = $GLOBALS['_CFG']['level'];
	
	// 获得直接下级商家数
	$agent = $user -> where(array(
		'parent1' => $user_info['id']
	)) -> count();
	
	// 获得所有下级商户数
	$agent_all = $user -> where(array(
		'parent1|parent2|parent3' => $user_info['id']
	)) -> count();
	
	// 获得所有订单数
	$orders = M('order') -> where(array('user_id' => $user_info['id'], 'status' => 4)) -> count();
	
	// 从高等级到低等级判断
	for($i = count($config)-1; $i>0; $i--){
		if($agent >= $config[$i]['agent'] && $agent_all >= $config[$i]['agent_all'] && $orders >= $config[$i]['orders'] && $user_info['sales'] >= $config[$i]['sales']){
			$user -> where(array('id='.$user_info['id'])) -> save(array(
				'level' => $i,
				'dist' => $GLOBALS['_CFG']['level'][$i]['dist']
			)); //setField('level', $i);
			break;
		}
	}
	return;
}

// 根据用户信息取得推广二维码路径信息
function get_qrcode_path($user){
	if(!is_array($user)){
		$user = M('user') -> find($user);
	}
	
	$path = './Public/qrcode/'.date('ym/d/',$user['sub_time']);
	return array(
			'path'		=> $path,
			'new'		=> $path.$user['id'].'_dragondean.jpg',
			'head' 		=> $path.$user['id'].'_head.jpg',
			'qrcode'	=> $path.$user['id'].'_qrcode.jpg',
			'full_path' => $_SERVER['DOCUMENT_ROOT'] . __ROOT__ . substr($path,1)
		);
}

/** 添加财务日志
*	type => money:余额记录,points:积分记录
*/
function flog($user_id, $type, $money, $action){
	M('finance_log') -> add(array(
		'user_id' => $user_id,
		'type' => $type,
		'money' => $money,
		'action' => $action,
		'create_time' => NOW_TIME
	));
}

// 确认订单
function confirm_order($order_info){
	if(!is_array($order_info)){
		M('order') -> find($order_info);
	}
	
	if($order_info['status'] != 3)return;
	
	M('order') -> where(array('id' => $order_info['id'])) -> save(array(
		'status' => 4,
		'confirm_time' => NOW_TIME
	));
	
	// 将订单中的积分赠送到用户
	if($order_info['points_total'] >0 ){
		M('user') -> where(array('id='.$order_info['user_id'])) -> save(array(
			'points' => array('exp', 'points+'.$order_info['points_total'])
		));
		flog($order_info['user_id'], 'points', $order_info['points_total'],10);
	}
	// 将分成状态设置为已完成
	M('separate_log') -> where('order_id='.$order_info['id']) -> setField('status', 4);
	
	// 循环对分成添加到分销商账户
	$separate_logs = M('separate_log') -> where('order_id='.$order_info['id']) -> select();
	foreach((array)$separate_logs as $separate_log){
		
		M('user') -> where('id='.$separate_log['user_id']) -> save(array(
			'money' => array('exp', 'money+'.$separate_log['money']), //余额
			'points' => array('exp', 'points+'.$separate_log['points']),//积分
			'separate_money' => array('exp', 'separate_money+'.$separate_log['money']), // 总提成金额
			'separate_points' => array('exp', 'separate_points+'.$separate_log['points']), // 总提成积分
			'sales' => array('exp', 'sales+'.$order_info['total']), // 总销售额
			'separate_order' => array('exp', 'separate_order+1'), // 总销售订单数
		));
		
		flog($separate_log['user_id'], 'money', $separate_log['money'],9);
		flog($separate_log['user_id'], 'points', $separate_log['points'],9);
	}
	
	// 更新用户登记
	update_level($order_info['user_id'], $GLOBALS['_CFG']['level']);
}
//获取星期方法
function get_week_time($date){
	$date=date('Y-m-d',$date);
	return get_week($date);
}
function get_week_str($date){
	$date=date('Y-m-d',strtotime($date));
	return get_week($date);
}
function get_week($date_str){
	$arr=explode("-", $date_str);
	$year=$arr[0];
	$month=sprintf('%02d',$arr[1]);
	$day=sprintf('%02d',$arr[2]);
	$hour = $minute = $second = 0;
	$strap = mktime($hour,$minute,$second,$month,$day,$year);
	//获取数字型星期几
	$number_wk=date("w",$strap);
	//自定义星期数组
	$weekArr=array("日","一","二","三","四","五","六");
	//获取数字对应的星期
	return $weekArr[$number_wk];
}
/**
 * 将数组转为key->list的键值对形式
 * @param array $list 要转换的数组
 * @param string $idKey  指定的key名
 * @return array key->list数组
 */
function idList($list, $idKey = "id") {
	if (! empty ( $list )) {
		foreach ( $list as $value ) {
			$idList [$value [$idKey]] = $value;
		}
	}
	return $idList;
}
/**
 * 获取数组中指定key的值，以逗号‘,’分隔
 * @param array $list 要获取数组源
 * @param string $key 要获取的key名
 * @return string key的值（逗号','分隔）
 */
function idStr($list, $key = "id") {
	if (! empty ( $list )) {
		foreach ( $list as $value ) {
			$id [] = $value [$key];
		}
	}
	return implode ( ",", $id );
}

/**
 * 整数变为小数
 * @param type $num 数字
 * @param type $format 需要几位小数 统一0来填充
 * @return type
 */
function int_decimal($num, $format = 1)
{
	$num_arr = explode('.', $num);

	if (count($num_arr) > 1)
		return $num;
	$num_arr = str_repeat(0, $format);
	return $num . '.' . $num_arr;
}
/**
 * 撒很难过船图片
 * @param unknown $field
 * @return 0 上传错误 1保存出错  成功返回url地址
 */
function _upload($field){
	if(empty($field))
		$field = 'file';
			
	if($_FILES[$field]['size'] < 1 && $_FILES[$field]['size']>0){
		return 0;
	}else{
		$ext = _get_ext($_FILES[$field]['name']);
		$new_name = _get_new_name($ext, 'images');
		if(move_uploaded_file($_FILES[$field]['tmp_name'], $new_name['fullname'])){
			return $new_name['fullname'];
		}else
			return 1;
	}
}
/**
 *	根据文件名获取后缀
 */
function _get_ext($file_name){
	return substr(strtolower(strrchr($file_name, '.')),1);
}

/**
 *	根据文件类型(后缀)生成文件名和路径
 *	@param return array('name', 'fullname' )
 *	* 文件名取时间戳和随机数的36进制而不是62进制是为了防止windows下大小写不敏感导致文件重名
 */
function _get_new_name($ext, $dir = 'default'){
	$name 		= date('His') . substr(microtime(),2,8) . rand(1000,9999) . '.' . $ext;
	$path 		= './Public/upload/' . $dir . date('/ym/d') .'/';

	// 如果路径不存在则递归创建
	if(!is_dir($path)){
		mkdir($path, 0777, 1);
	}

	return array(
			'name'		=> $name,
			'fullname'	=> $path . $name
	);
}

function error($font, $state = '1')
{
	if (empty($data))
	{
		$data = array ();
	}
	$data = array (
			'ret' => (int) $state,
			'reason' => $font,
			'data' => array (),
			'server_time' => NOW_TIME
	);
	if (empty($data['data']))
	{
		unset($data['data']);
	}
	return_json($data);
}

function success($data = array ())
{
	if (empty($data))
	{
		$data = array ();
	}
	$data = array (
			'ret' => 0,
			'reason' => 'OK',
			'data' => $data,
			'server_time' => NOW_TIME
	);
	if (empty($data['data']))
	{
		unset($data['data']);
	}
	return_json($data);
}

function return_json($arr)
{
	$result = is_array($arr) ? json_encode($arr) : $arr;
	exit($result);
}

function _send_ver($module,$mobile,$item=null){
	$signArray = array(
		0=>array("signName"=>"注册验证","templateId"=>"SMS_13255368","templateName"=>"用户注册验证码"),
		1=>array("signName"=>"身份验证","templateId"=>"SMS_13255372","templateName"=>"身份验证验证码"),
		2=>array("signName"=>"登录验证","templateId"=>"SMS_13255370","templateName"=>"登录确认验证码"),
		3=>array("signName"=>"登录验证","templateId"=>"SMS_13255369","templateName"=>"登录异常验证码"),
		4=>array("signName"=>"活动验证","templateId"=>"SMS_13255367","templateName"=>"活动确认验证码"),
		5=>array("signName"=>"变更验证","templateId"=>"SMS_13255366","templateName"=>"修改密码验证码"),
		6=>array("signName"=>"变更验证","templateId"=>"SMS_13255365","templateName"=>"信息变更验证码"),
		7=>array("signName"=>"身份验证","templateId"=>"SMS_33445042","templateName"=>"找回密码验证码"),
	);
	import('Org.Alidayu.top.TopClient');
    import('Org.Alidayu.top.ResultSet');
    import('Org.Alidayu.top.RequestCheckUtil');
    import('Org.Alidayu.top.TopLogger');
    import('Org.Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
    $c = new \TopClient;
    $c->appkey = C('AlidayuAppKey');  
    $c->secretKey = C('AlidayuAppSecret');
    $c->format = 'json';
    $req = new \AlibabaAliqinFcSmsNumSendRequest;
    //$req ->setExtend( "123456" );	//回传参数 原样返回 可选
    $req ->setSmsType( "normal" );
    $req ->setSmsFreeSignName($signArray[$module]['signName']);//来源于配置短信签名 下面列表中有签名名称
    $req ->setSmsTemplateCode($signArray[$module]['templateId']); //配置短信模板 列表中有模板id
    $req ->setRecNum($mobile); //手机号
    $code=rand(111111,999999);
    $product = "瑞钱包商城";
    $smsParam['code'] = (string)$code;
    $smsParam['product'] = (string)$product;
    if(!empty($item)){
    	$smsParam['item'] = (string)$item;
    }
    $req ->setSmsParam( json_encode($smsParam) ); //变量来源于 配置短信模板 点击列表中的详情 模板内容的变量 
    $resp = $c ->execute( $req );
    $log_data=array(
    		'module'=>$module,
    		'mobile'=>$mobile,
    		'ver_num'=>$code,
    		'create_time'=>NOW_TIME,
    );
    if (isset($result->code)){
    	$log_data['status'] = 0;
    }else{
    	$log_data['status'] = 1;
    }
    M('Ver_log')->add($log_data);
    return $resp;
}
